import attachmentService, { type PageListReq } from "@/api/services/system/attachmentService";
import { TableToolbar } from "@/components/grid/TableToolbar";
import { Upload } from "@/components/upload";
import { Button, Card, Form, Input, Modal, Space, Upload as AntdUpload } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import type { UploadFile, UploadProps } from "antd/es/upload/interface";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import type { SysAttachment } from "./entity";

export default function SysAttachmentPage() {
	const [loading, setLoading] = useState(false);
	const [queryParams, setQueryParams] = useState<PageListReq>({
		fileName: undefined,
		fileType: undefined,
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<SysAttachment[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");

	// 上传相关状态
	const [uploadModalVisible, setUploadModalVisible] = useState(false);
	const [fileList, setFileList] = useState<UploadFile[]>([]);
	const [uploading, setUploading] = useState(false);

	//字典项

	// 定义表格列
	const columns: ColumnsType<SysAttachment> = [
		{
			title: "文件地址",
			key: "fileUrl",
			dataIndex: "fileUrl",
		},
		{
			title: "文件名",
			key: "fileName",
			dataIndex: "fileName",
		},
		{
			title: "文件类型",
			key: "fileType",
			dataIndex: "fileType",
		},
		{
			title: "文件大小",
			key: "fileSize",
			dataIndex: "fileSize",
		},
		{
			title: "备注",
			key: "remark",
			dataIndex: "remark",
		},
		{
			title: "操作",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => handleDownLoad(record.id)}>
						下载
					</Button>
				</Space>
			),
		},
	];

	// 状态管理
	const [selectedValues, setSelectedValues] = useState<string[]>(() =>
		columns.filter((col) => col.key !== "operation").map((col) => String(col.key!)),
	);

	// 处理过滤后的列配置
	const filteredColumns = useMemo(() => {
		return [
			// 显示选中的列
			...columns.filter(
				(col) => selectedValues.includes(String(col.key)) || col.key === "operation", // 始终包含操作列
			),
		].sort((a, b) => {
			// 保持原始顺序
			const originalIndex = columns.findIndex((c) => c.key === a.key);
			const targetIndex = columns.findIndex((c) => c.key === b.key);
			return originalIndex - targetIndex;
		});
	}, [selectedValues]);

	const fetchPageList = () => {
		setLoading(true);
		attachmentService
			.pageList(queryParams)
			.then((res) => {
				setList(res.records);
				setTotal(res.total);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	//组件加载时获取组织机构数据
	useEffect(() => {
		fetchPageList();
	}, [queryParams]);

	//触发分页控件
	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	//删除附件方法
	const handleDelete = async () => {
		try {
			setLoading(true);
			await attachmentService.remove(selectedRowKeys);
			toast.success("删除附件成功");
			setSelectedRowKeys([]); // 清空选中项
			fetchPageList(); // 重新加载列表
		} catch (error) {
			toast.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	// 处理上传按钮点击
	const handleUpload = () => {
		setUploadModalVisible(true);
	};

	// 处理上传模态窗关闭
	const handleUploadModalCancel = () => {
		setUploadModalVisible(false);
		setFileList([]);
	};

	// 处理文件上传
	const handleFileUpload = async () => {
		if (fileList.length === 0) {
			toast.warning("请选择要上传的文件");
			return;
		}

		setUploading(true);

		// 上传每个文件
		for (const file of fileList) {
			if (file.originFileObj) {
				// 使用修改后的uploadFile方法
				await attachmentService
					.uploadFile(file.originFileObj)
					.then((res) => {
						toast.success("文件上传成功");
            setUploadModalVisible(false);
            fetchPageList();
					})
					.catch((error) => {
						toast.error(`上传失败: ${error.message || "未知错误"}`);
					})
					.finally(() => {
						setUploading(false);
            
					});
			}
		}
	};

	// 处理文件列表变化
	const handleFileListChange: UploadProps["onChange"] = ({ fileList: newFileList }) => {
		setFileList(newFileList);
	};

	// 上传前检查
	const beforeUpload = (file: File) => {
		// 这里可以添加文件类型、大小等检查
		const isLt10M = file.size / 1024 / 1024 < 10;
		if (!isLt10M) {
			toast.error("文件必须小于10MB!");
			return AntdUpload.LIST_IGNORE;;
		}
		return true;
	};

	//下载文件
	const handleDownLoad = (attachmentId: React.Key) => {
		attachmentService.downloadFile(attachmentId);
	};

	return (
		<>
			{/* 查询条件 */}
			<Card className="mb-4">
				<Form
					layout="inline"
					onFinish={(values) => {
						// 处理查询条件
						setQueryParams((prev) => ({
							...prev,
							...values,
							page: 1,
						}));
					}}
				>
					<Form.Item name="fileName" label="文件名">
						<Input placeholder="请输入文件名" allowClear />
					</Form.Item>
					<Form.Item name="fileType" label="文件类型">
						<Input placeholder="请输入文件类型" allowClear />
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button
							className="ml-2"
							onClick={() => {
								// 重置查询条件
								setQueryParams({ page: 1, pageSize: 10 });
							}}
						>
							重置
						</Button>
					</Form.Item>
				</Form>
			</Card>
			<div className="h-4" />
			{/* 表格数据 */}
			<Card>
				<div className="flex justify-between mb-4">
					<div className="flex gap-2">
						<Button type="primary" onClick={handleUpload}>
							上传
						</Button>
						<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
							删除
						</Button>
					</div>
					<TableToolbar
						onRefresh={() => setQueryParams((prev) => ({ ...prev }))}
						onSizeChange={setTableSize}
						columns={columns}
						selectedValues={selectedValues}
						onColumnChange={setSelectedValues}
					/>
				</div>
				<Table
					rowKey="id"
					size={tableSize}
					scroll={{ x: "max-content" }}
					loading={loading}
					pagination={{
						total,
						current: queryParams.page,
						pageSize: queryParams.pageSize,
						onChange: handlePageChange,
					}}
					columns={filteredColumns}
					dataSource={list}
					rowSelection={{
						type: "checkbox",
						selectedRowKeys: selectedRowKeys,
						onChange: (selectedKeys) => {
							setSelectedRowKeys(selectedKeys as string[]);
						},
					}}
				/>
			</Card>

			{/* 上传文件模态窗 */}
			<Modal
				title="上传文件"
				open={uploadModalVisible}
				onCancel={handleUploadModalCancel}
				footer={[
					<Button key="cancel" onClick={handleUploadModalCancel}>
						取消
					</Button>,
					<Button key="upload" type="primary" loading={uploading} onClick={handleFileUpload}>
						上传
					</Button>,
				]}
			>
				<Upload
					beforeUpload={beforeUpload}
					onChange={handleFileListChange}
					fileList={fileList}
					multiple={false}
					thumbnail={false}
				/>
				<div className="mt-4 text-gray-500">单个文件大小不超过10MB</div>
			</Modal>
		</>
	);
}
